<template>
  <a-modal
    :zIndex="zIndex"
    :title="title"
    :visible="visible"
    @cancel="handleCancel"
    width="850px"
    :cancelText="$t('关闭')"
    :confirmLoading="confirmLoading"
  >
    <template slot="footer">
      <a-row :gutter="24">
        <a-col :span="12">
          <div style="text-align: left" v-if="!dataForm.id">
            <a-checkbox v-model="isContinue" @change="changeAddState"></a-checkbox> {{ $t('连续添加') }}
          </div>
        </a-col>
        <a-col :span="12">
          <a-button @click="handleCancel">{{ $t('取消') }}</a-button>
          <a-button type="primary" @click="handleOk" v-if="!disable">{{ $t('保存') }}</a-button>
        </a-col>
      </a-row>
    </template>
    <div style="height: 500px; overflow-y: auto" ref="modalForm">
      <div style="margin-left: 10px">
        <a-form-model
          ref="dataForm"
          :rules="rules"
          :model="dataForm"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          v-enterToNext
        >
          <a-row>
            <div style="margin: 0 0 10px -10px; color: black; font-weight: 500; font-size: 15px">
              {{ $t('基本信息') }}
            </div>
            <a-col :span="12">
              <a-form-model-item prop="couponType" style="margin-bottom: 10px" :label="$t('券类型')">
                <j-dict-select-tag
                  type="list"
                  v-model="dataForm.couponType"
                  dictCode="bis_goods_infor.coupon_type"
                  :placeholder="$t('请选择券类型')"
                  :disabled="disable || edit_disable"
                  @change="handleChangeCouponType"
                />
              </a-form-model-item>
              <a-form-model-item prop="code" style="margin-bottom: 10px" :label="$t('券编码')">
                <a-input v-model="dataForm.code" ref="code" :disabled="disable"></a-input>
              </a-form-model-item>
              <a-form-model-item prop="name" style="margin-bottom: 10px" :label="$t('券名称')">
                <a-input v-model="dataForm.name" :disabled="disable"></a-input>
              </a-form-model-item>
              <a-form-model-item prop="kind" style="margin-bottom: 10px" :label="$t('分类')">
                <a-tree-select
                  show-search
                  :filterTreeNode="filterTreeNode"
                  :disabled="disable"
                  allowClear
                  v-model="dataForm.kind"
                  :dropdownStyle="{ maxHeight: '250px', overflow: 'auto' }"
                  :tree-data="treeData"
                  :search-placeholder="$t('请选择')"
                  :getPopupContainer="triggerNode => { return triggerNode.parentNode || document.body }"
                />
              </a-form-model-item>
              <a-form-model-item prop="value" style="margin-bottom: 10px" :label="$t('面额')">
                <div style="height:40px;display:flex;align-items: center">
                  <a-input-number v-model="dataForm.value" :disabled="disable"
                    :formatter="formatter"
                    :parser="parser"
                    style="width: 100%;"
                    :precision="2"
                  ></a-input-number>
                  <a-tooltip>
                    <template slot="title">{{
                      $t('代表该券的价值，用于小程序上的展示。')
                    }}</template>
                    <a-icon type="question-circle" style="padding-left: 5px" />
                  </a-tooltip>
                </div>
              </a-form-model-item>
              <a-form-model-item prop="price" style="margin-bottom: 10px" :label="$t('售价')">
                <a-input-number v-model="dataForm.price" :disabled="disable" @change="changePrice"
                  :formatter="formatter"
                  :parser="parser"
                  style="width: 100%;"
                  :precision="2"
                ></a-input-number>
              </a-form-model-item>
            </a-col>
            <a-col :span="12" style="padding-right: 0">
              <a-form-model-item
                prop="picture"
                :label="$t('图片')"
                :labelCol="{ span: 6 }"
                :wrapperCol="{ span: 18 }"
              >
                <div>
                  <j-upload
                    v-model="dataForm.picture"
                    accept="jpg,jpeg,png,gif,webp"
                    fileType="image"
                    :disabled="disable"
                  ></j-upload>
                  <div style="color: #f7b926; line-height: 1.2">{{ $t('建议尺寸：750*750，大小不要超过500KB') }}</div>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="dataForm.couponType == 0">
              <a-form-model-item
                :label="$t('满减规则')"
                :labelCol="{ span: 4 }"
                :wrapperCol="{ span: 18 }"
                style="margin-bottom: 10px"
              >
                {{ $t('订单金额满') }} <a-input-number v-model="dataForm.full" :disabled="disable" /> {{ $t('元可用') }}
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="dataForm.couponType == 0">
              <a-form-model-item
                :label="$t('适用卖品')"
                :labelCol="{ span: 4 }"
                :wrapperCol="{ span: 18 }"
                style="margin-bottom: 10px"
              >
                <a-radio-group
                  v-model="dataForm.allowGoodsType"
                  @change="getTypeValue"
                  :disabled="disable"
                >
                  <a-radio v-for="item in allowGoodsList" :value="item.value" :key="item.value">{{
                    item.text
                  }}</a-radio>
                </a-radio-group>
                <br />
                <a-checkbox-group
                  :span="24"
                  v-if="goodsState == '1'"
                  v-model="form"
                  style="margin-top: 6px;"
                >
                  <a-checkbox
                    style="margin-left: 8px"
                    :value="item.value"
                    v-for="item in formList"
                    :key="item.value"
                    :disabled="disable"
                    >{{ item.title }}</a-checkbox
                  >
                </a-checkbox-group>
                <div v-if="goodsState == '2'">
                  <div
                    style="display: inline-block; margin-right: 10px"
                    v-for="(item, index, key) in goodSortList"
                    :key="key"
                  >
                    {{ item.name }}
                    <a-icon
                      @click="delGoodsKind(item, index, 'exclude')"
                      style="color: red; cursor: pointer"
                      type="close"
                      :disabled="disable"
                    />
                  </div>
                  <span>
                    <a href="javascript:void(0);" @click="addKinds('exclude')" :disabled="disable">{{
                      $t('添加分类')
                    }}</a>
                  </span>
                </div>
                <div v-if="goodsState == '3'">
                  <div
                    style="display: inline-block; margin-right: 10px"
                    v-for="(item, index, key) in goodsList"
                    :key="key"
                  >
                    {{ item.name }}
                    <a-icon
                      @click="delGoods(item, index, 'exclude')"
                      style="color: red; cursor: pointer"
                      type="close"
                      :disabled="disable"
                    />
                  </div>
                  <span>
                    <a href="javascript:void(0);" @click="addGoods(0)" :disabled="disable">{{
                      $t('添加商品')
                    }}</a>
                  </span>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="(goodsState == '0' || goodsState == '1' || goodsState == '2') && dataForm.couponType == 0">
              <a-form-model-item
                :label="$t('排除卖品')"
                :labelCol="{ span: 4 }"
                :wrapperCol="{ span: 18 }"
                style="margin-bottom: 10px"
              >
                <div>
                  <div
                    style="display: inline-block; margin-right: 10px; margin-left: 4px"
                    v-for="(item, index, key) in delGoodsList"
                    :key="key"
                  >
                    {{ item.name }}
                    <a-icon
                      @click="delDelGoods(item)"
                      style="color: red; cursor: pointer"
                      type="close"
                      :disabled="disable"
                    />
                  </div>
                  <span>
                    <a
                      href="javascript:void(0);"
                      @click="addGoods(1)"
                      :disabled="disable"
                      >{{ $t('添加商品') }}</a
                    >
                  </span>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="dataForm.couponType == 1">
              <a-form-model-item
                :label="$t('赠送')"
                :labelCol="{ span: 4 }"
                :wrapperCol="{ span: 20 }"
                style="margin-bottom: 10px"
                required
              >
                <div>
                  {{ $t('代币') }}：<a-input
                    style="width: 80px"
                    v-model="dataForm.coin"
                    :disabled="disable"
                  ></a-input>
                  {{ $t('彩票') }}：<a-input
                    style="width: 80px"
                    v-model="dataForm.lottery"
                    :disabled="disable"
                  ></a-input>
                  {{ $t('积分') }}：<a-input
                    style="width: 80px"
                    v-model="dataForm.integral"
                    :disabled="disable"
                  ></a-input>
                  {{ $t('A币') }}：<a-input
                    style="width: 80px"
                    v-model="dataForm.points"
                    :disabled="disable"
                  ></a-input>
                  {{ $t('A票') }}：<a-input
                    style="width: 80px"
                    v-model="dataForm.alottery"
                    :disabled="disable"
                  ></a-input>
                </div>
                <div style="margin-top: 8px">
                  {{ $t('限时币') }}：
                  <a-select
                    style="width: 200px"
                    show-search
                    allow-clear
                    :placeholder="$t('请选择')"
                    v-model="seclimittimecoinId"
                    @search="handleSearch3"
                    @change="hangeleChange3"
                    :filterOption="false"
                    :disabled="disable"
                  >
                    <a-select-option v-for="(item, i) in limitTimeCoins" :key="i" :value="item.id">{{
                      item.name
                    }}</a-select-option>
                  </a-select>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="dataForm.couponType == 2">
              <a-form-model-item style="margin-bottom: 10px" :label="$t('选择门票')" :labelCol="{ span: 4 }" :wrapperCol="{ span: 7 }" required>
                <a-select
                  show-search
                  v-model="secticketId"
                  @search="handleSearch1"
                  @change="hangeleChange1"
                  :placeholder="$t('请选择门票')"
                  :filterOption="false"
                  :disabled="disable"
                >
                  <a-select-option v-for="(item, i) in tickets" :key="i" :value="item.id"
                    >{{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="dataForm.couponType == 3">
              <a-form-model-item style="margin-bottom: 10px" :label="$t('选择商品')" :labelCol="{ span: 4 }" :wrapperCol="{ span: 7 }" required>
                <a-select
                  show-search
                  v-model="secgoodsId"
                  @search="handleSearch2"
                  @change="hangeleChange2"
                  :placeholder="$t('请选择商品')"
                  :filterOption="false"
                  :disabled="disable"
                >
                  <a-select-option v-for="(item, i) in goods" :key="i" :value="item.id"
                    >{{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                prop="comment"
                :label="$t('备注')"
                :labelCol="{ span: 4 }"
                :wrapperCol="{ span: 18 }"
              >
                <a-textarea v-model="dataForm.comment" ref="comment" :rows="3" :disabled="disable" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row v-if="taxSetting != 0">
            <div style="margin: 0 0 10px -10px; color: black; font-weight: 500; font-size: 15px">
              {{ $t('销售设置') }}
            </div>
            <a-col :span="24">
              <a-row>
                <a-col :span="8" v-if="taxSetting == 1">
                  <a-form-model-item
                    prop="allowTax"
                    style="margin-bottom: 5px; margin-left: 10px"
                    :labelCol="{ span: 0 }"
                    :wrapperCol="{ span: 24 }"
                  >
                    <a-checkbox
                      :checked="dataForm.allowTax == 1"
                      :disabled="disable"
                      @change="(e) => changeSelectState(e, 'allowTax', 1)"
                      >{{ $t('销售加税') }}</a-checkbox
                    >
                  </a-form-model-item>
                </a-col>
                <a-col :span="8" v-if="taxSetting == 2">
                  <a-form-model-item
                    prop="allowTax"
                    style="margin-bottom: 5px; margin-left: 10px"
                    :labelCol="{ span: 0 }"
                    :wrapperCol="{ span: 24 }"
                  >
                    {{$t('其中税费')}}：{{ dataForm.taxPrice }}
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <div style="margin: 0 0 10px -10px; color: black; font-weight: 500; font-size: 15px">
                {{ $t('应用限制') }}
              </div>
              <a-row style="margin-bottom: 14px;margin-left: 10px;">
                <a-col :span="3">{{ $t('上架状态') }}：</a-col>
                <a-col :span="20">
                  <a-radio-group v-model="dataForm.state" ref="state" :disabled="disable">
                    <a-radio value="Y">{{ $t('上架') }}</a-radio>
                    <a-radio value="N">{{ $t('下架') }}</a-radio>
                  </a-radio-group>
                </a-col>
              </a-row>
              <a-row style="margin-left: 10px;">
                <a-col :span="3">{{ $t('有效期') }}：</a-col>
                <a-col :span="21">
                  <a-form-model-item prop="validityType" :labelCol="{ span: 2 }" :wrapperCol="{ span: 22 }">
                    <a-radio-group v-model="dataForm.validityType" ref="validityType" @change="limitChangeValid">
                      <div style="margin-bottom: 14px;">
                        <a-radio value="0" :disabled="disable">{{ $t('不限期') }}</a-radio>
                      </div>
                      <div>
                        <a-radio value="1" :disabled="disable">{{ $t('指定日期') }}：</a-radio>
                        <j-date
                          :disabled="!islimitValid"
                          v-model="dataForm.startDate"
                          :placeholder="$t('请选择日期')"
                          style="width: 180px"
                        ></j-date>
                        ~
                        <j-date
                          :disabled="!islimitValid"
                          v-model="dataForm.endDate"
                          :placeholder="$t('请选择日期')"
                          style="width: 180px"
                        ></j-date>
                      </div>
                      <div style="margin-top: 20px">
                        <a-radio value="2" :disabled="disable">{{ $t('指定天数') }}：</a-radio>
                        <i18n path="valid-period2" tag="span">
                          <a-input-number
                            place="startDays"
                            v-model="dataForm.startDays"
                            style="width: 64px; margin: 0 4px"
                            :disabled="islimitValid || disable"
                            :min="0"
                          />
                          <a-input-number
                            place="validDays"
                            v-model="dataForm.validDays"
                            style="width: 64px; margin: 0 4px"
                            :disabled="islimitValid || disable"
                            :min="0"
                          />
                        </i18n>
                      </div>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
          <!-- <a-row style="margin-left: 20px" v-if="stateDisable != 11">
            <div style="margin: 10px 0 10px -30px; color: black; font-weight: 500; font-size: 15px">{{$t('第三方核销')}}</div>
            <a-form-model-item>
              <div style="display: inline-block" v-for="(item, index, key) in dataForm.bisGoodsThirdList" :key="key">
                {{ item.channel_dictText }}: {{ item.thirdCode }}
                <a-icon
                  @click="delGoodsThird(item, index, 'exclude')"
                  style="color: #1890ff; cursor: pointer"
                  type="close"
                  :disabled="disable"
                  v-if="!disable"
                />，
              </div>
              <span>
                <a href="javascript:void(0);" @click="addGoodsThird()" style="margin-left: 10px" v-if="!disable"
                  >{{$t('添加')}}</a
                >
              </span>
            </a-form-model-item>
          </a-row> -->
        </a-form-model>
      </div>
    </div>
    <!-- <bis-goods-third-modal ref="goodsThirdmodel" @ok="addGoodsThirdCallback"></bis-goods-third-modal> -->
    <add-kind-modal ref="kindForm" @ok="addKindCallback"></add-kind-modal>
    <add-goods-modal ref="goodsForm" @ok="addGoodsCallback"></add-goods-modal>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import AddKindModal from './AddKindModal'
import AddGoodsModal from './AddGoodsModal'
import {formatter, parser} from "@api/comm";
/* import BisGoodsThirdModal from './BisGoodsThirdModal' */

export default {
  name: 'CouponsModal',
  components: {
    AddKindModal,
    AddGoodsModal,
    /* BisGoodsThirdModal, */
  },
  data() {
    return {
      formatter,
      parser,
      zIndex: 1001,
      form: this.$form.createForm(this),
      model: {},
      title: '',
      confirmLoading: false,
      dataForm: {
        couponType: 0,
        code: '',
        name: '',
        full: '0',
        form: 9,
        validityType: '0',
        allowGoodsType: '0',
        allowTax: 1,
        state: 'Y',
        startDate: '',
        endDate: '',
        startDays: '',
        validDays: '',
        coin: '',
        lottery: '',
        integral: '',
        points: '',
        alottery: '',
        bisGoodsThirdList: [],
      },
      form: [], //形态
      treeData: [],
      deviceShow: false,
      visible: false,
      labelCol: {
        xs: { span: 20 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 14 },
      },
      rules: {
        couponType: [{ required: true, message: this.$t('请选择券类型') }],
        name: [{ required: true, message: this.$t('请输入券名称') }],
        kind: [{ required: true, message: this.$t('请选择分类') }],
        value: [
          {
            required: true,
            message: this.$t('请输入正整数或零，支持两位小数'),
            pattern: /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*)|0)$/,
          },
        ],
        price: [
          {
            required: true,
            message: this.$t('请输入正整数或零，支持两位小数'),
            pattern: /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*)|0)$/,
          },
        ],
      },
      url: {
        add: '/goods/bisGoodsInfor/add',
        edit: '/goods/bisGoodsInfor/edit',
      },
      disable: false,
      gamedisable: true,
      stateDisable: '',
      islimitValid: false,

      goodsState: '',
      formList: [],
      goodSortList: [],
      goodsList: [],
      delGoodsList: [],
      allowGoodsList: [],
      edit_disable: false,
      tickets: [],
      secticketId: undefined,
      secticket: {},
      goods: [],
      secgoodsId: undefined,
      secgoods: {},
      limitTimeCoins: [],
      seclimittimecoinId: undefined,
      seclimittimecoins: [],
      isContinue: true,
      taxSetting: 0,
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    addGoodsThird() {
      this.$refs.goodsThirdmodel.edit()
    },
    delGoodsThird(item) {
      this.dataForm.bisGoodsThirdList.forEach((col) => {
        if (col.channel == item.channel && col.thirdCode == item.thirdCode) {
          let index = this.dataForm.bisGoodsThirdList.indexOf(col)
          this.dataForm.bisGoodsThirdList.splice(index, 1)
        }
      })
    },
    addGoodsThirdCallback(item) {
      getAction('/sys/dict/getDictText/bis_goods_third.channel/' + item.channel).then((res) => {
        if (res.success) {
          item.channel_dictText = res.result
          var b = true
          if (this.dataForm.bisGoodsThirdList && this.dataForm.bisGoodsThirdList.length > 0) {
            this.dataForm.bisGoodsThirdList.forEach((col) => {
              if (col.channel == item.channel && col.thirdCode == item.thirdCode) {
                b = false
                return
              }
            })
          } else {
            this.$set(this.dataForm, 'bisGoodsThirdList', [])
          }
          if (b) {
            this.dataForm.bisGoodsThirdList.push(item)
          } else {
            this.$message.warning('该第三方渠道商品已存在')
            return
          }
        }
      })
    },
    add(value) {
      let that = this
      that.visible = true
      that.stateDisable = value
      that.isContinue = localStorage.getItem('goodsAddInfo')
        ? JSON.parse(localStorage.getItem('goodsAddInfo')).state
        : true
      that.islimitValid = true
      that.goodsState = ''
      that.form = []
      that.tickets = []
      that.goods = []
      that.limitTimeCoins = []
      that.secticketId = undefined
      that.secgoodsId = undefined
      that.seclimittimecoinId = undefined
      that.edit_disable = false
      that.dataForm = {
        couponType: 0,
        code: '',
        name: '',
        full: '0',
        price: '0',
        validityType: '0',
        allowGoodsType: '0',
        allowMemberDiscount: 'Y',
        allowTax: 1,
        state: 'Y',
        notAllowGoods: '',
        form: 9,
        coin: '',
        lottery: '',
        integral: '',
        points: '',
        alottery: '',
      }
      that.edit(that.dataForm)
    },
    edit(record, state) {
      let that = this
      that.secticketId = undefined
      that.secgoodsId = undefined
      that.seclimittimecoinId = undefined
      that.stateDisable = record.form
      that.formList = []
      that.goodSortList = []
      that.delGoodsList = []
      that.disable = state
      that.islimitValid = state
      that.select()
      that.taxSetting = localStorage.getItem('taxSetting')
      if (record.id) {
        that.edit_disable = true
      }
      initDictOptions('bis_goods_infor.form').then((res) => {
        if (res.success) {
          res.result.forEach((col) => {
            if (col.value != '9') {
              that.formList.push(col)
            }
          })
        }
      })
      initDictOptions('bis_goods_infor.allow_goods_type').then((res) => {
        if (res.success) {
          that.allowGoodsList = res.result
        }
      })
      that.visible = true
      if (record.validityType == '1') {
        that.islimitValid = true
      } else {
        that.islimitValid = false
      }
      record.allowGoodsType = record.allowGoodsType.toString()
      that.goodsState = record.allowGoodsType
      if (record.allowGoodsType == '1') {
        that.form = record.allowGoods.split(',')
      }
      if (record.allowGoodsType == '2') {
        let sortList = []
        sortList = record.allowGoods.split(',')
        sortList.forEach((col) => {
          that.addKindCallback(col)
        })
      }
      if (record.allowGoodsType == '3') {
        let goodsList = []
        goodsList = record.allowGoods.split(',')
        goodsList.forEach((col) => {
          that.addGoodsCallback(col, '0')
        })
      }
      if (record.allowGoodsType == '0' || record.allowGoodsType == '1' || record.allowGoodsType == '2') {
        let delGoodsList = []
        if (record.notAllowGoods != '' && record.notAllowGoods != undefined) {
          delGoodsList = record.notAllowGoods.split(',')
          delGoodsList.forEach((col) => {
            that.addGoodsCallback(col, '1')
          })
        }
      }
      if (record.id) {
        getAction('/goods/bisGoodsThird/list', { goodsId: record.id, pageSize: 999 }).then((res) => {
          if (res.success && res.result.total > 0) {
            this.$set(this.dataForm, 'bisGoodsThirdList', res.result.records)
          }
        })
        if (record.couponType == 1) {
          that.handleSearch3('')
        }
        if (record.couponType == 2) {
          that.handleSearch1('')
        }
        if (record.couponType == 3) {
          that.handleSearch2('')
        }
        getAction('/goods/bisGoodsInfor/queryBisGoodsPackageByMainId', { id: record.id }).then((res) => {
          if (res.success) {
            if(res.result.length > 0){
              if (record.couponType == 1) {
                that.seclimittimecoinId = res.result[0].goodsId
                that.seclimittimecoin = {
                  id: res.result[0].goodsId,
                  form: res.result[0].goodsForm,
                  name: res.result[0].goodsInfo[0].name,
                }
              }
              if (record.couponType == 2) {
                that.secticketId = res.result[0].goodsId
                that.secticket = {
                  id: res.result[0].goodsId,
                  form: res.result[0].goodsForm,
                  name: res.result[0].goodsInfo[0].name,
                }
              }
              if (record.couponType == 3) {
                that.secgoodsId = res.result[0].goodsId
                that.secgoods = {
                  id: res.result[0].goodsId,
                  form: res.result[0].goodsForm,
                  name: res.result[0].goodsInfo[0].name,
                }
              }
            }
          } else {
            that.$message.error(res.message)
          }
        })
      }
      that.dataForm = Object.assign({}, record)
      if (!that.dataForm.id) {
        let param = {
          pageNo: 1,
          pageSize: 9999,
          column: 'sort',
          order: 'asc',
          code: 'YHJ',
        }
        getAction('/goods/bisGoodsKind/rootList', param).then((res) => {
          if (res.success) {
            if (res.result.records.length > 0) {
              that.$set(that.dataForm, 'kind', res.result.records[0].id)
            }
          }
        })
      }
      that.$nextTick(() => {
        that.$refs.modalForm.scrollTop = 0
      })
    },
    addKinds() {
      this.$refs.kindForm.edit()
    },
    addGoods(value) {
      this.$refs.goodsForm.edit(value)
    },
    addGoodsCallback(id, value) {
      let querydata = {}
      querydata.pageNo = 1
      querydata.pageSize = 999
      querydata.id = id
      getAction('/goods/bisGoodsInfor/list', querydata).then((res) => {
        if (res.success) {
          let aa = {}
          aa.name = res.result.records[0].name
          aa.id = res.result.records[0].id
          if (value == '0') {
            this.goodsList.push(aa)
          } else {
            this.delGoodsList.push(aa)
          }
        }
      })
    },
    addKindCallback(kindid) {
      getAction('/goods/bisGoodsKind/childList', { id: kindid }).then((res) => {
        if (res.success) {
          let aa = {}
          aa.name = res.result.records[0].name
          aa.id = res.result.records[0].id
          this.goodSortList.push(aa)
        }
      })
    },
    delGoodsKind(item) {
      this.goodSortList.forEach((col) => {
        if (col.id == item.id) {
          let index = this.goodSortList.indexOf(col)
          this.goodSortList.splice(index, 1)
        }
      })
    },
    delGoods(item) {
      this.goodsList.forEach((col) => {
        if (col.id == item.id) {
          let index = this.goodsList.indexOf(col)
          this.goodsList.splice(index, 1)
        }
      })
    },
    delDelGoods(item) {
      this.delGoodsList.forEach((col) => {
        if (col.id == item.id) {
          let index = this.delGoodsList.indexOf(col)
          this.delGoodsList.splice(index, 1)
        }
      })
    },
    limitChangeValid(e) {
      if (e.target.value == '1') {
        this.islimitValid = true
      } else {
        this.islimitValid = false
      }
    },
    getTypeValue(e) {
      this.goodsState = e.target.value
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      let that = this
      let querydata = {}
      that.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (that.dataForm.name == '') {
            that.$message.warn(that.$t('请输入券名称'))
            return
          }
          that.dataForm.allowGoodsType = that.goodsState
          if (that.dataForm.validityType == '1') {
            if (that.dataForm.startDate == undefined || that.dataForm.endDate == undefined) {
              that.$message.warning(that.$t('请选择指定日期'))
              return
            }
          }
          if (that.dataForm.validityType == '2') {
            if (that.dataForm.startDays == undefined || that.dataForm.validDays == undefined) {
              that.$message.warning(that.$t('请输入指定天数'))
              return
            }
          }
          if (that.dataForm.couponType == 0) {
            switch (that.goodsState) {
              case '1':
                if (that.form.length == 0) {
                  that.$message.warn(that.$t('请选择商品形态'))
                  return
                } else {
                  that.dataForm.allowGoods = that.form.join(',')
                }
                break
              case '2':
                let list = []
                if (that.goodSortList.length == 0) {
                  that.$message.warn(that.$t('请选择商品分类'))
                  return
                } else {
                  that.goodSortList.forEach((col) => {
                    list.push(col.id)
                  })
                  that.dataForm.allowGoods = list.join(',')
                }
                break
              case '3':
                let goods = []
                if (that.goodsList.length == 0) {
                  that.$message.warn(that.$t('请选择商品'))
                  return
                } else {
                  that.goodsList.forEach((col) => {
                    goods.push(col.id)
                  })
                  that.dataForm.allowGoods = goods.join(',')
                }
                break
              default:
                break
            }
            let delGoods = []
            that.delGoodsList.forEach((col) => {
              delGoods.push(col.id)
            })
            that.dataForm.notAllowGoods = delGoods.join(',')
          }
          if (
            that.dataForm.couponType == 1 &&
            !that.isEmpty(that.dataForm.coin) &&
            !that.isEmpty(that.dataForm.lottery) &&
            !that.isEmpty(that.dataForm.alottery) &&
            !that.isEmpty(that.dataForm.integral) &&
            !that.isEmpty(that.dataForm.points) &&
            that.seclimittimecoinId === undefined
          ) {
            that.$message.warning(that.$t('代币、彩票、积分、A币、A票、限时币至少有一项不为0或空'))
            return
          }
          if (that.dataForm.couponType == 1 && that.seclimittimecoinId !== undefined) {
            let dtl = {
              goodsForm: that.seclimittimecoin.form,
              goodsId: that.seclimittimecoin.id,
              amount: 1,
              isGift: 1,
            }
            that.dataForm.bisGoodsPackageList = [dtl]
          }
          if (that.dataForm.couponType == 2) {
            if (!that.secticketId) {
              that.$message.warning(that.$t('请选择门票'))
              return
            } else {
              let dtl = {
                goodsForm: that.secticket.form,
                goodsId: that.secticket.id,
                amount: 1,
                isGift: 1,
              }
              that.dataForm.bisGoodsPackageList = [dtl]
            }
          }
          if (that.dataForm.couponType == 3) {
            if (!that.secgoodsId) {
              that.$message.warning(that.$t('请选择商品'))
              return
            } else {
              let dtl = {
                goodsForm: that.secgoods.form,
                goodsId: that.secgoods.id,
                amount: 1,
                isGift: 1,
              }
              that.dataForm.bisGoodsPackageList = [dtl]
            }
          }
          that.dataForm.allowSale = 'Y'
          querydata = that.dataForm
          let httpurl = ''
          let method = ''
          if (!that.dataForm.id) {
            httpurl += that.url.add
            method = 'post'
          } else {
            httpurl += that.url.edit
            method = 'put'
          }
          that.confirmLoading = true
          httpAction(httpurl, querydata, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                if (that.dataForm.id || !that.isContinue) {
                  that.close()
                } else {
                  that.initDataForm()
                }
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    filterTreeNode(inputValue, treeNode) {
      // 假设输入格式为 "级别:关键词" 如 "2:电器"
      const match = inputValue.match(/([123]):(.+)/)
      if (match) {
        const level = parseInt(match[1])
        const keyword = match[2]
        const nodeLevel = this.getNodeLevel(treeNode)
        
        if (nodeLevel !== level) return false
        return treeNode.data.props.title.includes(keyword)
      }
      
      // 默认搜索
      return treeNode.data.props.title.includes(inputValue)
    },
    getNodeLevel(node) {
      let level = 1
      let parent = node.parent
      while (parent) {
        level++
        parent = parent.parent
      }
      return level
    },
    select() {
      let that = this
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'sort'
      param.order = 'asc'
      getAction('/goods/bisGoodsKind/rootList', param).then((res) => {
        if (res.success) {
          that.allChildKind = []
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            that.treeData = that.getDataByResult(res.result.records)
          } else {
            that.treeData = []
          }
        } else {
          that.$alert(res.message, '提示', {
            confirmButtonText: '确定',
            callback: (action) => {},
          })
        }
      })
    },
    getHasChild(record) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = record.id
      getAction('/goods/bisGoodsKind/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            record.children = that.getDataByResult(res.result.records)
            that.treeData = [...that.treeData]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      let that = this
      return result.map((item) => {
        if (item.hasChild == 0 && item.key != '0') {
          that.allChildKind.push(item.key)
        }
        return item
      })
    },
    submitCallback() {
      this.$emit('ok')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    handleChangeCouponType(e) {
      let that = this
      that.tickets = []
      that.secticketId = undefined
      that.goods = []
      that.secgoodsId = undefined
      that.limitTimeCoins = []
      that.seclimittimecoinId = undefined
      that.dataForm.coin = ''
      that.dataForm.lottery = ''
      that.dataForm.integral = ''
      that.dataForm.points = ''
      that.dataForm.alottery = ''
      if (e == 1) {
        that.getLimitTimeCoins('')
      }
      if (e == 2) {
        that.getTickets('')
      }
      if (e == 3) {
        that.getGoods('')
      }
    },
    handleSearch1(val) {
      let that = this
      that.getTickets(val)
    },
    handleSearch2(val) {
      let that = this
      that.getGoods(val)
    },
    handleSearch3(val) {
      let that = this
      that.getLimitTimeCoins(val)
    },
    getTickets(val, gid) {
      let that = this,
        query = {}
      query.pageIndex = 1
      query.pageSize = 9999
      query.form = '3,4'
      query.goodsInfo = val
      if (gid) {
        query.id = gid
      }
      getAction('/goods/bisGoodsInfor/list', query).then((res) => {
        if (res.success) {
          that.tickets = res.result.records
        }
      })
    },
    getGoods(val, gid) {
      let that = this,
        query = {}
      query.pageIndex = 1
      query.pageSize = 9999
      query.form = '1,12'
      query.goodsInfo = val
      if (gid) {
        query.id = gid
      }
      getAction('/goods/bisGoodsInfor/list', query).then((res) => {
        if (res.success) {
          that.goods = res.result.records
        }
      })
    },
    getLimitTimeCoins(val, gid) {
      let that = this,
        query = {}
      query.pageIndex = 1
      query.pageSize = 9999
      query.form = '15'
      query.goodsInfo = val
      if (gid) {
        query.id = gid
      }
      getAction('/goods/bisGoodsInfor/list', query).then((res) => {
        if (res.success) {
          that.limitTimeCoins = res.result.records
        }
      })
    },
    hangeleChange1() {
      let that = this
      that.secticket = that.tickets.filter((tk) => {
        return tk.id == that.secticketId
      })[0]
    },
    hangeleChange2() {
      let that = this
      that.secgoods = that.goods.filter((gd) => {
        return gd.id == that.secgoodsId
      })[0]
    },
    hangeleChange3() {
      let that = this
      that.seclimittimecoin = that.limitTimeCoins.filter((gd) => {
        return gd.id == that.seclimittimecoinId
      })[0]
    },
    isEmpty(val) {
      if (val === '0') {
        return false
      } else if (val) {
        return true
      } else {
        return false
      }
    },
    changeAddState() {
      localStorage.setItem('goodsAddInfo', JSON.stringify({ state: this.isContinue }))
    },
    initDataForm() {
      let that = this
      that.islimitValid = true
      that.goodsState = ''
      that.form = []
      that.tickets = []
      that.goods = []
      that.limitTimeCoins = []
      that.secticketId = undefined
      that.secgoodsId = undefined
      that.seclimittimecoinId = undefined
      that.edit_disable = false
      that.dataForm = {
        couponType: 0,
        code: '',
        name: '',
        full: '0',
        price: '0',
        validityType: '0',
        allowGoodsType: '0',
        allowMemberDiscount: 'Y',
        allowTax: 1,
        state: 'Y',
        notAllowGoods: '',
        form: 9,
        coin: '',
        lottery: '',
        integral: '',
        points: '',
        alottery: '',
      }
      that.$refs.code.focus()
      that.edit(that.dataForm)
    },
    changeSelectState(e, key, type) {
      if (type == 1) {
        this.$set(this.dataForm, key, e.target.checked ? 1 : 0)
      }
    },
    changePrice() {
      if(this.taxSetting == 2){
        this.$set(this.dataForm,'taxPrice',(this.dataForm.price - (this.dataForm.price / ( 1 + localStorage.getItem('taxRate') / 100))).toFixed(2))
      }
    },
  },
}
</script>
<style scoped>
.bold-font {
  font-weight: bold;
}
</style>